$(function(){

    layui.use(['layer'],function(){

        var layer = layui.layer;

        var SUB_NAME;
        var SUB_ID;
        var PAGE;
        var SUB_TYPE;

        var attachmentData = new Array();	//定义存放附件的对象

        // 定义webuploader配置
        var webuploader_option = {
            auto: false,
            server: ThinkPHP['AJAX'] + '/BBS/upload',
            pick: '#filePicker',
            fileVal: 'Filedata',
            accept: {
                title: 'file',
                extensions: 'zip,rar,jpg,png,jpeg,doc,xls,gif,xlsx,docx,pdf',
            },
            method: 'POST',
        };

        // 实例化webuploader
        var uploader = WebUploader.create(webuploader_option);

        // 添加到队列时
        uploader.on('fileQueued', function (file) {
            var fileItem = '<div class="file-item" id="' + file.id + '">' +
                '<div class="pull-left"><i class="file-icon file-icon-ext-' + file.ext + '"></i> ' + file.name + '</div>' +
                '<div class="pull-right"><i class="icon-remove" title="移除该文件"></i></div>' +
                '<div class="clearfix"></div>' +
                '</div>';
            $(webuploader_option.pick).next().append(fileItem);
        });

        // 上传之前
        uploader.on('uploadBeforeSend', function (block, data, headers) {

            data.SUB_NAME = SUB_NAME;
            data.DIR = '/BBS/';

        });

        //上传成功时
        uploader.on('uploadSuccess', function (file, response) {	//文件了上传成功后触发

            if (response.flag > 0) {
                //当文件上传成功后添加到attachmentData
                var attachmentObject = new Object();
                attachmentObject.savename = response.savename;
                attachmentObject.ext = response.ext;
                attachmentObject.path = response.path;
                attachmentData.push(attachmentObject);
            } else {
                layer.closeAll();
                layer.msg(response.msg, {icon: 2, time: 2000});
            }
        });

        // 所有文件上传结束时
        uploader.on('uploadFinished', function () {

            $.ajax({
                url: ThinkPHP['AJAX'] + '/BBS/insertAttachment',
                type: 'POST',
                data: {
                    SUB_NAME: SUB_NAME,
                    SUB_TYPE: SUB_TYPE,
                    SUB_ID: SUB_ID,
                    attachments: JSON.stringify(attachmentData)
                },
                dataType: 'json',
                success: function (response) {
                    if (response.flag > 0) {
                        layer.closeAll();
                        layer.msg(response.msg, {icon: 1, time: 2000});
                        setTimeout(function () {
                            location.href = 'http://' + ThinkPHP['HTTP_HOST'] + '/BBS/detail/id/' + SUB_ID + '/p/'+ PAGE;
                            //location.reload();
                        }, 2000);
                    } else {
                        layer.closeAll();
                        layer.msg(response.msg, {icon: 2, time: 2000});
                    }
                }
            });
        });

        // 上传错误时
        uploader.on('error', function (code) {
            var msg = '';
            switch (code) {
                case 'Q_EXCEED_NUM_LIMIT':
                    msg = '只能上传一个文件';
                    break;
                case 'Q_EXCEED_SIZE_LIMIT':
                    msg = '文件大小超出限制';
                    break;
                case 'Q_TYPE_DENIED':
                    msg = '文件格式不允许';
                    break;
                case 'F_DUPLICATE':
                    msg = '文件已存在';
                    break;
                default:
                    msg = code;
            }
            layer.msg(msg, {icon: 2, time: 2000});
        });

        $('.uploader-file-queue').on('click', '.icon-remove', function () {

            var id = $(this).parent().parent().attr('id');
            // 删除队列中的文件
            uploader.removeFile(id, true);
            // 删除dom节点
            $(this).parent().parent().remove();

        });

        // 回复区 点击回复出现输入框
        $('.message-board').on('click', '.reply-btn', function () {

            $('.reply-context').css('display', 'none');

            $(this).parents('.floor').find('.reply-context').css('display', 'block')
            $(this).parents('.floor').find('.reply-context textarea').focus();

        });

        // 回复区 点击取消隐藏输入框
        $('.message-board').on('click', '.close-reply', function () {
            $(this).parents('.reply-context').hide();
        });

        // 回复提交
        $('.message-board').on('click', '.reply-submit', function () {

            var strValue = $(this).parents('.reply-form').find('.reply-textarea').val();
            var string = strValue.replace(/\&nbsp\;/ig, ' ');

            //如果内容为空不允许提交
            if ($.trim(string).length < 1) {
                layer.msg('内容不得为空', {icon: 2, time: 2000});
                return false;
            }

            var data = new Object();

            data.context = ($(this).parents('.reply-form').find('.reply-textarea').val());
            data.id = ($(this).parents('.reply-form').find('input[name = l_id]').val());
            data.l_id = ($(this).parents('.reply-form').find('input[name = id]').val());
            data.count = $.trim($(this).parents('.floor').children('.reply-hin').text());
            var index = layer.load(2, {
                shade: [0.5, '#fff'] //0.1透明度的白色背景
            });
            $.ajax({
                url: '/BBS/reply',
                type: 'POST',
                data: data,
                dataType: 'json',

                success: function (response) {
                    if (response.flag > 0) {
                        layer.msg(response.msg, {icon: 1, time: 2000})
                        setTimeout(function () {
                            location.href = '/BBS/detail?id=' + response.id + '&p=' + response.pg + '&rd=' + Math.random().toString(36).substr(2) + '#comments';
                        }, 2000);
                    } else {
                        layer.msg(response.msg, {icon: 2, time: 2000})
                        setTimeout(function () {
                            layer.close(index);
                            location.reload();
                        }, 2000)
                    }
                }
            });

            return false;
        });

        // 提交评论
        $('#submit-discuss-content').click(function (evt) {

            // 判断是否输入的空格 回车 空
            var strValue = editor.getValue();
            var string = strValue.replace(/\&nbsp\;/ig, ' ');

            if (!$.trim(string).length) {
                layer.msg('内容不能为空！', {icon: 2, time: 2000});
                return false;
            }

            // 拼装提交数据
            var result = {};
            result.content = editor.getValue();
            result.id = $('#submit-discuss-content').attr('discuss_id');
            result.count = $(this).attr('count');

            var loading = layer.load(2, {
                shade: [0.5, '#fff'] //0.1透明度的白色背景
            });

            $.ajax({
                url: '/BBS/reply',
                data: result,
                type: 'POST',
                dataType: 'json',
                success: function (response) {
                    if (response.flag > 0) {
                        SUB_NAME = response.id;
                        SUB_TYPE = response.type;
                        SUB_ID = response.flag;
                        PAGE = response.pg;
                        if (uploader.getFiles().length > 0) {
                            uploader.upload();
                        } else {
                            layer.msg(response.msg, {icon: 1, time: 2000});
                            setTimeout(function () {
                                location.href = '/BBS/detail?id=' + response.id + '&p=' + response.pg + '&rd=' + Math.random().toString(36).substr(2) + '#comments';
                            }, 2000);
                        }
                    } else {
                        layer.msg(response.msg, {icon: 2, time: 2000});
                        setTimeout(function () {
                            layer.close(loading);
                        }, 2000);
                    }
                }
            })

        })


        $('.zan .thumbs-up').click(function () {
            var _this = $(this);
            $.post('/BBS/zan', {
                id: _this.attr('bbs-id')
            }, function(response) {
                if (!response.code) {
                    if (_this.hasClass('active')) {
                        _this.removeClass('active');
                    } else {
                        $('.WB_like').show();
                        _this.addClass('active');
                        setTimeout(function () {
                            $('.WB_like').hide();
                        }, 1000);
                    }

                    var html = zanUsers(response.data.users);
                    $('.zan-list').html(html);

                    $('.zan-count').html(response.data.count > 0 ? response.data.count : '');

                    $('.author-zan-count').html(response.data.authorZanCount);
                } else {
                    layer.alert(response.msg);
                }
            }, 'json');
        });

        function zanUsers(users)
        {
            var html = '';
            if (users.length) {
                html += '<i class="glyphicon glyphicon-thumbs-up thumbs-up active mr-10"></i>';
            }
            html += '<span class="zan-users">';
            for(var i = 0; i < users.length; i++) {
                if ((i + 1) == users.length) {
                    html += '<a href="javascript:;">' + users[i] + '</a>';
                } else {
                    html += '<a href="javascript:;">' + users[i] + '、</a>';
                }
            }
            html += '</span>';

            return html;
        }
    })

});
